package com.music.message.utils;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.google.gson.Gson;
import com.music.common.core.constant.Constants;
import com.music.common.core.enums.ExceptionCode;
import com.music.common.core.exception.CustomException;
import com.music.common.core.utils.StringUtils;
import com.music.common.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * Author 史豪通
 * Date 2024/10/11 19:41
 */
@Component
public class MessageUtils {
    @Resource
    private IAcsClient iAcsClient;
    @Resource
    private SendSmsRequest sendSmsRequest;
    @Resource
    RedisService redisService;
    @Value("${ali.send}")
    private boolean send;

    public void send(String phone, String codeKeyPreFix) {
        sendSmsRequest.setPhoneNumbers(phone);

        Map<String, String> message = new HashMap<>();
        String code = (System.currentTimeMillis() + "").substring(9);
        message.put("code", code);
        System.out.println("send phone -> " + phone + " code -> " + code);
        sendSmsRequest.setTemplateParam(JSONObject.toJSONString(message));

        // 验证码放redis里
        redisService.setCacheObject(codeKeyPreFix + phone, code, 5L, TimeUnit.MINUTES);

        try {
            if (send) {
                iAcsClient.getAcsResponse(sendSmsRequest);
            }
            System.out.println("send phone -> " + phone + " code -> " + code + " successfully!");
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }
    }

    public void sendUser(String phone) {
        send(phone, Constants.MESSAGE_USER_CODE);
    }

    public void check(String phone, String code, String codeKeyPreFix) {
        String redisCode = redisService.getCacheObject(codeKeyPreFix + phone);
        if (Objects.isNull(redisCode)) throw new CustomException(ExceptionCode.INVALID_CAPTCHA_OUT_OF_TIME);
        if (!StringUtils.equals(redisCode, code)) throw new CustomException(ExceptionCode.INVALID_KAPTCHA);
        System.out.println("check phone -> " + phone + " code -> " + code + " successfully!");
    }

    public void checkUser(String phone, String code) {
        check(phone, code, Constants.MESSAGE_USER_CODE);
    }
}
